<?php

namespace App\Models\Customer;

use App\Models\Concerns\ScopeFilterable;
use App\Observers\BosCleanObserver;
use App\Services\Utils\Bosable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

/**
 * Class HairAsset
 * @package App\Models\Customer
 *
 * @method static self create(array $hair_asset)
 * @method static self find(string $id)
 * @method static self filterGender(string $gender)
 * @see HairAsset::scopeFilterGender
 *
 * @mixin Builder
 */
class HairAsset extends Model
{
    use Bosable, ScopeFilterable;

    protected $key_bos_key_prefix = 'hair_asset/preview/';  // 2.5d发型试戴的 发型预览图

    protected $hair_asset_prefix = 'hair_asset/hair/';          // 2.5d发型试戴的 素材图

    protected $table = 'hair_assets';

    protected $guarded = [];

    public $bos_columns = ['hair_preview', 'assets_bin', 'assets_png'];

    /**
     * @param $hair_preview
     * @throws \Exception
     */
    public function setHairPreviewAttribute($hair_preview)
    {
        if (is_file($hair_preview)) {
            $this->attributes['hair_preview'] = $this->uploadPostFile($hair_preview, $this->key_bos_key_prefix);
        }
    }

    /**
     * @return null|string
     */
    public function getHairPreviewAttribute()
    {
        if (!$this->attributes['hair_preview']) return null;

        return $this->getStaticUrl($this->attributes['hair_preview']);
    }

    /**
     * @param $assets_bin
     * @throws \Exception
     */
    public function setAssetsBinAttribute($assets_bin)
    {
        if (is_file($assets_bin)) {
            $this->attributes['assets_bin'] = $this->uploadPostFileWithName($assets_bin, $this->hair_asset_prefix . $this->attributes['assets_dir'] . '/', 'hair_mesh.bin');
        }
    }

    /**
     * @return null|string
     */
    public function getAssetsBinAttribute()
    {
        if (!$this->attributes['assets_bin']) return null;

        return $this->getStaticUrl($this->attributes['assets_bin']);
    }

    /**
     * @param $assets_png
     * @throws \Exception
     */
    public function setAssetsPngAttribute($assets_png)
    {
        if (is_file($assets_png)) {
            $this->attributes['assets_png'] = $this->uploadPostFileWithName($assets_png, $this->hair_asset_prefix . $this->attributes['assets_dir'] . '/', 'hair.png');
        }
    }

    /**
     * @return null|string
     */
    public function getAssetsPngAttribute()
    {
        if (!$this->attributes['assets_png']) return null;

        return $this->getStaticUrl($this->attributes['assets_png']);
    }

    /**
     * 注册删除 bosKey 事件绑定
     */
    protected static function boot()
    {
        parent::boot();

        /*
         * 监听bos清理事件
         */
        self::observe(BosCleanObserver::class);
    }

    public function scopeFilterGender(Builder $query, $gender)
    {
        if (is_null($gender)) return $query;
//        dd($gender);

        return $query->where('gender', $gender);
    }

}
